<?php
/**
 * Created by PhpStorm.
 * User: 杜磊磊
 * Date: 2020/5/30
 * Time: 19:19
 */
namespace app\admin\controller;

use think\facade\View;
use app\admin\model\AdminUser;
use think\facade\Session;
// use app\admin\validate\AdminUser as Bbb;
// use think\exception\ValidateException;

class Login extends AdminBase
{
    public function initialize()
    {
        if($this->isLogin()){
            return $this->redirect(url("index/index"),302);
        }
    }

    public function index()
    {
        return View::fetch();
    }

    public function check()
    {
        if(!$this->request->isPost()){
            return show(config("status.error"),"请求方式错误");
        }
        $username = $this->request->param("username","","trim");
        $password = $this->request->param("password","","trim");
        $captcha = $this->request->param("captcha","","trim");
        //使用框架自带验证器验证
        $data = [
            'username' => $username,
            'password' => $password,
            'captcha' => $captcha,
        ];
        $validate = new \app\admin\validate\AdminUser();
        if (!$validate->check($data)){
            return show(config("status.error"),$validate->getError());
        }
        // try {
        //     validate(Bbb::class)->check($data);
        // } catch (ValidateException $e) {
        //     // 验证失败 输出错误信息
        //     dump($e->getError());
        // }

        try {
            $adminUserObj = new \app\admin\business\AdminUser();
            $result = $adminUserObj->login($data);
        }catch (\Exception $e){
            return show(config("status.error"),$e->getMessage());
        }

        if($result){
            return show(config("status.success"),'登陆成功');
        }
        return show(config("status.error"),'登陆失败');

    }
}